package cn.net.xyan.easy.webapp.base.frontend.provider;

import cn.net.xyan.easy.gwt.client.EZGwt;
import cn.net.xyan.easy.gwt.client.model.Page;
import cn.net.xyan.easy.gwt.client.model.Pageable;
import cn.net.xyan.easy.gwt.client.model.SortOrder;
import cn.net.xyan.easy.gwt.client.model.TableCellDataModel;
import cn.net.xyan.easy.webapp.base.api.dto.QueryUserRsq;
import cn.net.xyan.easy.webapp.base.frontend.service.SystemConfigControllerAsync;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by zarra on 16/3/10.
 */
public class UserProvider extends AsyncDataProvider<TableCellDataModel> {

    SystemConfigControllerAsync scca = EZGwt.create(SystemConfigControllerAsync.class);

    int pageSize = 40;

    public static class UserTableModel implements TableCellDataModel{

        QueryUserRsq rsq;

        public UserTableModel(QueryUserRsq rsq){
            this.rsq = rsq;
        }
        @Override
        public Class<?> classForColumnIndex(int index) {
            return String.class;
        }

        @Override
        public <T> T valueForColumnIndex(Class<T> tClass, int index) {
            switch (index){
                case 0:
                    return (T)rsq.getUsername();
                case 1:
                    return (T)rsq.getRealName();
                case 2:
                    return (T)rsq.getEmail();
                case 3:
                    return (T)rsq.getStatus().toString();
            }
            return null;
        }
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Override
    protected void onRangeChanged(HasData<TableCellDataModel> display) {
        final Range range = display.getVisibleRange();
        Pageable pageable = new Pageable(range.getStart()/pageSize,pageSize);
        pageable.getSortOrders().add(new SortOrder("username"));
        pageable.getSortOrders().add(new SortOrder("realName",SortOrder.DESC));
        scca.allUsers(pageable, new MethodCallback<Page<QueryUserRsq>>()  {
            @Override
            public void onFailure(Method method, Throwable exception) {

            }

            @Override
            public void onSuccess(Method method, Page<QueryUserRsq> response) {
                List<TableCellDataModel> result = new LinkedList<>();
                updateRowCount(response.getTotalElements(),true);
                for (QueryUserRsq rsq:response.getContent()){
                    result.add(new UserTableModel(rsq));
                }
                if(result.size()>0) {
                    updateRowData(range.getStart(), result);
                }

            }
        });
    }
}
